#include "CTiledLayer.h"
#include "Global Variables.h"


CTiledLayer::CTiledLayer(CTexture *pImage, int column, int row, int cellSize)
{
	m_pImage	= pImage;
	m_iColumn	= column;
	m_iRow		= row;
	m_iCellSize	= cellSize;

	m_iNumCellWidth	 = (g_ScreenWidth / cellSize) + 1;
	m_iNumCellHeight = (g_ScreenHeight / cellSize) + 1;
	

	m_ppMap = new int*[row];
	for (int i = 0; i < column; i++) 
	{
		m_ppMap[i] = new int[column];
	}
}


CTiledLayer::~CTiledLayer()
{
	if (m_ppMap != NULL)
	{
		for (int i = 0; i < m_iRow; i++)
		{
			delete[] m_ppMap[i];
		}
		delete[] m_ppMap;
	}
}


void CTiledLayer::SetCell(int column, int row, int index)
{
	if (column > m_iColumn || row > m_iRow)
		return;
	
	m_ppMap[row][column] = index;
}


void CTiledLayer::Draw(RECT rect, int angle)
{
	int leftCell	= rect.left / m_iCellSize;
	int leftOffset	= rect.left % m_iCellSize;
	int topCell		= rect.top / m_iCellSize;
	int topOffset	= rect.top % m_iCellSize;

	int x, y;
	
	D3DXMatrixTransformation2D(&mtxTransform,
							NULL, 0.0f, NULL,												// scaling
							&D3DXVECTOR2(g_ScreenWidth / 2, g_ScreenHeight / 2), angle,		// rotation
							NULL);															// translation
	m_pImage->m_pSpriteHandler->SetTransform(&mtxTransform);

	for (int i = topCell, size1 = i + m_iNumCellHeight; i < size1; i++)
	{
		for (int j = leftCell, size2 = j + m_iNumCellWidth; j < size2; j++)
		{
			x = (j - leftCell) * m_iCellSize - leftOffset;
			y = (i - topCell) * m_iCellSize - topOffset;
			DrawCell(m_ppMap[i][j], x, y, angle);
		}
	}
}


void CTiledLayer::DrawCell(int index, int x, int y, int angle)
{
	RECT rect;
	rect.left = (index - 1) * m_iCellSize;
	rect.right = rect.left + m_iCellSize;
	rect.top = 0;
	rect.bottom = m_iCellSize;
	m_pImage->m_pSpriteHandler->Draw(m_pImage->m_pTexture, &rect, NULL, &D3DXVECTOR3(x, y, 0), 0xffffff);
}


BOOL CTiledLayer::IsCollision(int x, int y, int width, int height)
{
	int left	= (x + 1) / m_iCellSize;
	int top		= (y + 1) / m_iCellSize;
	int right	= (x + width) / m_iCellSize;
	int bottom  = (y + height) / m_iCellSize;

	return false;
}